/*
 * editProject.java
 *
 * Created on 22 de mayo de 2008, 9:44
 */
package jule;

import java.awt.Cursor;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import jule.clases.dbUtil;

import jule.clases.project.dbDataType;
import schemacrawler.crawl.SchemaCrawler;
//import schemacrawler.crawl.SchemaCrawlerOptions;
//import schemacrawler.crawl.SchemaInfoLevel;
import schemacrawler.schema.Column;
import schemacrawler.schema.Schema;
import schemacrawler.schema.Table;
import javax.sql.DataSource;


import java.sql.*;

import jule.clases.sf;

// for filechooser
import javax.swing.JFileChooser;
// for File
import java.io.*;

//  dddd

import javax.swing.text.View;
import javax.xml.ws.Response;
import jule.clases.dbUtil2;
import jule.clases.field;
import jule.clases.lo;
import jule.clases.project;
import jule.clases.relation;
import jule.clases.table;
import jule.clases.util;

import schemacrawler.schema.Database;
import schemacrawler.schema.NamedObject;
import schemacrawler.schemacrawler.SchemaCrawlerOptions;
import schemacrawler.schemacrawler.SchemaInfoLevel;
import schemacrawler.utility.SchemaCrawlerUtility;

/**
 *
 * @author  Administrador
 */
public class editProject extends javax.swing.JDialog {

    public static class COLUMN {

        public final static int TABLE_CAT = 1;
        public final static int TABLE_SCHEM = 2;
        public final static int TABLE_NAME = 3;
        public final static int COLUMN_NAME = 4;
        public final static int DATA_TYPE = 5;
        public final static int TYPE_NAME = 6;
        public final static int COLUMN_SIZE = 7;
        public final static int BUFFER_LENGTH = 8;
        public final static int DECIMAL_DIGITS = 9;
        public final static int NUM_PREC_RADIX = 10;
        public final static int NULLABLE = 11;
        public final static int REMARKS = 12;
        public final static int COLUMN_DEF = 13;
        public final static int SQL_DATA_TYPE = 14;
        public final static int SQL_DATETIME_SUB = 15;
        public final static int CHAR_OCTET_LENGTH = 16;
        public final static int ORDINAL_POSITION = 17;
        public final static int IS_NULLABLE = 18;
    }

    /** Creates new form editProject */
    public editProject(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        butSaveConnection.setVisible(false);
        butSaveConnectionOnly.setVisible(false);
    }    // esta es la conexion de newProject y juleView
    // es decir la forma de pasarle al jFrame anterior los datos...
    protected project NProject;
    public static final String PROP_NPROJECT = "nProject";

    /**
     * Get the value of NProject
     *
     * @return the value of NProject
     */
    public project getNProject() {
        return NProject;
    }

    /**
     * Set the value of NProject
     *
     * @param NProject new value of NProject
     */
    public void setNProject(project nProject) {
        project oldNProject = this.NProject;
        this.NProject = nProject;
        propertyChangeSupport.firePropertyChange(PROP_NPROJECT, oldNProject, nProject);
        nombre.setText(nProject.getName());
        host.setText(nProject.getHost());
        instance.setText(nProject.getInstance());
        port.setText(nProject.getPort());
        user.setText(nProject.getuser());
        password.setText(nProject.getpassword());
        database.setText(nProject.getdatabase());
        description.setText(nProject.getDescription());
        applicationDirectory.setText(nProject.getApplicationDirectory());
        projectTemplatesDirectory.setText(nProject.getProjectTemplatesDirectory());
        lo.comboSelectObject(jComboBox1, nProject.getTypeOfDataBase());

        butSaveConnection.setText("Refresh metadata");
        butSaveConnectionOnly.setVisible(true);
    }
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        panelDatos = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        nombre = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        host = new javax.swing.JTextField();
        user = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        description = new javax.swing.JTextField();
        database = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        applicationDirectory = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        password = new javax.swing.JPasswordField();
        port = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        butProbarConexion = new javax.swing.JButton();
        butSaveConnection = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        projectTemplatesDirectory = new javax.swing.JTextField();
        butWorkingDirectory = new javax.swing.JButton();
        butWorkingDirectory1 = new javax.swing.JButton();
        butSaveConnectionOnly = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        instance = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        info = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtHelp = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        jLabel2.setName("jLabel2"); // NOI18N

        panelDatos.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        panelDatos.setName("panelDatos"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(jule.JuleApp.class).getContext().getResourceMap(editProject.class);
        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        nombre.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        nombre.setName("nombre"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.nombre}"), nombre, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        host.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        host.setName("host"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.host}"), host, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        host.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                hostFocusLost(evt);
            }
        });
        host.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                hostPropertyChange(evt);
            }
        });

        user.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        user.setName("user"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.user}"), user, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        jLabel7.setText(resourceMap.getString("jLabel7.text")); // NOI18N
        jLabel7.setName("jLabel7"); // NOI18N

        description.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        description.setName("description"); // NOI18N

        database.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        database.setName("database"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.database}"), database, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel8.setText(resourceMap.getString("jLabel8.text")); // NOI18N
        jLabel8.setName("jLabel8"); // NOI18N

        applicationDirectory.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        applicationDirectory.setName("applicationDirectory"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.applicationDirectory}"), applicationDirectory, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel9.setText(resourceMap.getString("jLabel9.text")); // NOI18N
        jLabel9.setName("jLabel9"); // NOI18N

        password.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        password.setName("password"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.password}"), password, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        port.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        port.setName("port"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${NProject.port}"), port, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jLabel10.setText(resourceMap.getString("jLabel10.text")); // NOI18N
        jLabel10.setName("jLabel10"); // NOI18N

        jLabel11.setText(resourceMap.getString("jLabel11.text")); // NOI18N
        jLabel11.setName("jLabel11"); // NOI18N

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "None", "MySql", "PostgreSql", "SqlServer", "Jdbc", "SqlExpress" }));
        jComboBox1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jComboBox1.setName("jComboBox1"); // NOI18N
        jComboBox1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jComboBox1MouseClicked(evt);
            }
        });
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        butProbarConexion.setText(resourceMap.getString("butProbarConexion.text")); // NOI18N
        butProbarConexion.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        butProbarConexion.setName("butProbarConexion"); // NOI18N
        butProbarConexion.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butProbarConexionMouseClicked(evt);
            }
        });

        butSaveConnection.setText(resourceMap.getString("butSaveConnection.text")); // NOI18N
        butSaveConnection.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        butSaveConnection.setName("butSaveConnection"); // NOI18N
        butSaveConnection.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butSaveConnectionMouseClicked(evt);
            }
        });
        butSaveConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butSaveConnectionActionPerformed(evt);
            }
        });

        jLabel12.setText(resourceMap.getString("jLabel12.text")); // NOI18N
        jLabel12.setName("jLabel12"); // NOI18N

        projectTemplatesDirectory.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        projectTemplatesDirectory.setName("projectTemplatesDirectory"); // NOI18N

        butWorkingDirectory.setIcon(resourceMap.getIcon("butWorkingDirectory.icon")); // NOI18N
        butWorkingDirectory.setText(resourceMap.getString("butWorkingDirectory.text")); // NOI18N
        butWorkingDirectory.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        butWorkingDirectory.setName("butWorkingDirectory"); // NOI18N
        butWorkingDirectory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butWorkingDirectoryActionPerformed(evt);
            }
        });

        butWorkingDirectory1.setIcon(resourceMap.getIcon("butWorkingDirectory1.icon")); // NOI18N
        butWorkingDirectory1.setText(resourceMap.getString("butWorkingDirectory1.text")); // NOI18N
        butWorkingDirectory1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        butWorkingDirectory1.setName("butWorkingDirectory1"); // NOI18N
        butWorkingDirectory1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butWorkingDirectory1MouseClicked(evt);
            }
        });

        butSaveConnectionOnly.setText(resourceMap.getString("butSaveConnectionOnly.text")); // NOI18N
        butSaveConnectionOnly.setToolTipText(resourceMap.getString("butSaveConnectionOnly.toolTipText")); // NOI18N
        butSaveConnectionOnly.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        butSaveConnectionOnly.setName("butSaveConnectionOnly"); // NOI18N
        butSaveConnectionOnly.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                butSaveConnectionOnlyMouseClicked(evt);
            }
        });
        butSaveConnectionOnly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                butSaveConnectionOnlyActionPerformed(evt);
            }
        });

        jLabel13.setText(resourceMap.getString("jLabel13.text")); // NOI18N
        jLabel13.setName("jLabel13"); // NOI18N

        instance.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        instance.setName("instance"); // NOI18N

        javax.swing.GroupLayout panelDatosLayout = new javax.swing.GroupLayout(panelDatos);
        panelDatos.setLayout(panelDatosLayout);
        panelDatosLayout.setHorizontalGroup(
            panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelDatosLayout.createSequentialGroup()
                        .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel12)
                            .addComponent(jLabel9)
                            .addComponent(jLabel7)
                            .addComponent(jLabel8)
                            .addComponent(jLabel11)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nombre, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(password, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(database, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(user, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(jComboBox1, 0, 629, Short.MAX_VALUE)
                            .addComponent(description, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(applicationDirectory, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addComponent(projectTemplatesDirectory, javax.swing.GroupLayout.DEFAULT_SIZE, 629, Short.MAX_VALUE)
                            .addGroup(panelDatosLayout.createSequentialGroup()
                                .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel13)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(instance, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel10)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(butWorkingDirectory)
                            .addComponent(butWorkingDirectory1))
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelDatosLayout.createSequentialGroup()
                        .addComponent(butSaveConnectionOnly, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 221, Short.MAX_VALUE)
                        .addComponent(butProbarConexion, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(butSaveConnection, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14))))
        );
        panelDatosLayout.setVerticalGroup(
            panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelDatosLayout.createSequentialGroup()
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(host, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel13)
                    .addComponent(instance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10)
                    .addComponent(port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(35, 35, 35)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(database, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(description, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(applicationDirectory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(butWorkingDirectory))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel12)
                    .addComponent(projectTemplatesDirectory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(butWorkingDirectory1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(panelDatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(butSaveConnectionOnly, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(butProbarConexion, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(butSaveConnection, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
                .addContainerGap())
        );

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        info.setColumns(20);
        info.setRows(5);
        info.setName("info"); // NOI18N
        jScrollPane2.setViewportView(info);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelDatos, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(396, 396, 396)
                .addComponent(jLabel2)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(37, 37, 37))
                    .addComponent(panelDatos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 222, Short.MAX_VALUE)
                .addContainerGap())
        );

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jtHelp.setBackground(resourceMap.getColor("jtHelp.background")); // NOI18N
        jtHelp.setColumns(20);
        jtHelp.setFont(resourceMap.getFont("jtHelp.font")); // NOI18N
        jtHelp.setForeground(resourceMap.getColor("jtHelp.foreground")); // NOI18N
        jtHelp.setRows(5);
        jtHelp.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jtHelp.setName("jtHelp"); // NOI18N
        jScrollPane1.setViewportView(jtHelp);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 797, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 824, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 239, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void butProbarConexionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butProbarConexionMouseClicked
    panelDatos.setVisible(false);
    int seleccionado = jComboBox1.getSelectedIndex();
    boolean seguir = false;


    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    switch (seleccionado) {
        case 1: // mysql



            try {
                // vamos a probar la conexion...
                dbUtil db = new dbUtil();
                String mensaje = "";
                mensaje = dbUtil2.testDatabaseMysql(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                // mensaje = dbUtil.testDataSourceMySql(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                seguir = (mensaje.equals(""));
                if (seguir) {
                    // conexion exitosa
                    info.setText("Sucessful connection ...\n");
                } else {
                    // conexion exitosa
                    info.setText("Wrong connection...\n" + mensaje);
                    info.setText("Wrong connection...\n" + mensaje);
                }
            } catch (Exception ex) {
            }


            break;
        case 2: // postrgresql



            break;

        case 3: // sql server

            try {
                // vamos a probar la conexion...
                dbUtil db = new dbUtil();
                String mensaje = "";
                //mensaje = dbUtil.testDataSourceSqlServer(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                //  mensaje = dbUtil.testDataSourceSqlServerJtds(host.getText(), instance.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                mensaje = dbUtil2.testDatabaseSqlServer(host.getText(), instance.getText(), database.getText(), user.getText(), password.getText(), port.getText());


                seguir = mensaje.equals("");
                if (mensaje.equals("")) {
                    // conexion exitosa
                    info.setText("Sucessful connection ...\n");
                } else {
                    // conexion exitosa
                    info.setText("Wrong connection...\n" + mensaje);
                }
            } catch (Exception ex) {
            }


            break;

        case 4: //jdbc
            // vamos a probar la conexion...
            try {
                info.setText("Testing connection...\n");
                if (database.getText().contains(".")) {
                    info.append("Remember, dont use the dot character in the name of the dsn...\n");
                }
                dbUtil db = new dbUtil();
                String mensaje = "";
                mensaje = dbUtil.testDataSourceOdbc(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                seguir = (mensaje.equals(""));
                if (seguir) {
                    // conexion exitosa
                    info.append("Sucessful connection ...\n");
                } else {
                    // conexion exitosa
                    info.append("Wrong connection... /n" + mensaje);
                }
            } catch (Exception ex) {
            }
            break;

        case 5: //sqlExpress
            // vamos a probar la conexion...
            try {
                dbUtil db = new dbUtil();
                String mensaje = "";
                mensaje = dbUtil.testDataSourceSqlExpress(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                seguir = (mensaje.equals(""));
                if (seguir) {
                    // conexion exitosa
                    info.setText("Sucessful connection ...\n");
                } else {
                    // conexion exitosa
                    info.setText("Wrong connection...\n" + mensaje);
                }
            } catch (Exception ex) {
            }
            break;
    }
    this.setCursor(Cursor.getDefaultCursor());
    panelDatos.setVisible(true);
    butSaveConnection.setVisible(seguir);
}//GEN-LAST:event_butProbarConexionMouseClicked
// tell us if the jdbc driver (jsdk) its loaded...

    public static void testJdbDriver() {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            System.out.println("sun.jdbc.odbc.JdbcOdbcDriver found");
        } catch (ClassNotFoundException cnfe) {
            System.out.println("Error: sun.jdbc.odbc.JdbcOdbcDriver not found");
        }
    }

private void butSaveConnectionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butSaveConnectionMouseClicked


    panelDatos.setVisible(false);
    int seleccionado = jComboBox1.getSelectedIndex();
    boolean seguir = false;


    // declaraciones para crear el proyecto...
    project proyectoActual = new project();
    ArrayList<table> tablas = new ArrayList<table>();
    ArrayList<field> campos = new ArrayList<field>();
    table tablitaActual = new table();
    field campoActual = new field();

    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    switch (seleccionado) {
        case 1: // mysql


            try {
//                // vamos a probar la conexion...
//                dbUtil db = new dbUtil();
//
//                final DataSource dataSource = dbUtil.makeDataSourceMySql(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
//                // Create the options
//                final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
//                options.setSchemaInfoLevel(SchemaInfoLevel.maximum());
//
//
//                /*
//                options.setShowStoredProcedures(false);
//                options.setTableInclusionRule(new InclusionRule("C.*",InclusionRule.EXCLUDE_NONE));
//                options.setColumnInclusionRule(new InclusionRule(InclusionRule.INCLUDE_ALL_PATTERN,Pattern.compile(".*ID")));
//                options.setTableTypes("TABLE");
//                options.setAlphabeticalSortForTableColumns(true);
//                 */
//
//                final String excludesTablesPattern = "^(_|SYS|EX|PM|TMP|(CDI|MGMT|DBA|USER|CI|SDD|ALL|RM|TMP|TEST|DWH|SAV|SAVE)_).+$";
//
//
//                // Get the schema definition
//                // changed to maximum to get the relations between tables...
////                final schemacrawler.crawl.DatabaseSchemaCrawler schema = schemacrawler.crawl.DatabaseSchemaCrawler SchemaCra.getSchema(dataSource,
////                        SchemaInfoLevel.maximum(),
////                        options);
//
//                final Database database = SchemaCrawlerUtility.getDatabase(dataSource.getConnection(), options);

                final Database databasex = dbUtil2.getDatabaseMysql(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                Schema schemax = null;

                if (databasex != null) {
                    //final Catalog[] catalog = databasex..getCatalogs();
                    final Schema[] catalog = databasex.getSchemas();
                    // lets search our database...
                    for (Schema schema : catalog) {
                        if (schema.getCatalogName().equalsIgnoreCase(database.getText())) {
                            schemax = schema;
                            break;
                        }
                    }
                }



                // final Schema schema = catalog[0];
                if (schemax != null) {
                    final Table[] tables = schemax.getTables();
                    for (int i = 0; i < tables.length; i++) {
                        final Table table = tables[i];
                        System.out.print(table);


                        // le sacamos todos los datos...
                        // si no empieza por sys o por schema
                        // (tablas del sistema sql server )
                        if (table.toString().indexOf("sys") == -1 && table.toString().indexOf("SCHEMA") == -1) {
                            tablitaActual = null;
                            tablitaActual = new table();

                            ArrayList<field> camposTablaActual = new ArrayList<field>();

                            tablitaActual.setName(table.getName());
                            tablitaActual.setTargetName(table.getName());
                            info.append("Found table : " + table.getName() + "\n");

//                            if (table instanceof View) {
//                                System.out.println(" (view)");
//                            } else {
//                                System.out.println();
//                            }


                            final Column[] columns = table.getColumns();
                            for (int j = 0; j < columns.length; j++) {
                                final Column column = columns[j];
                                System.out.println("-- " + column);

                                campoActual = null;
                                campoActual = new field();
                                campoActual.setNombre(column.getName());
//                                if (column.isPartOfPrimaryKey())
//                                    campoActual.setIsKey();

                                int tipo = column.getType().getType();
                                campoActual.setTipo(tipo);
                                campoActual.setTargetType(tipo);

                                campoActual.setisKey(column.isPartOfPrimaryKey());
                                campoActual.setisForeignKey(column.isPartOfForeignKey());
                                campoActual.setDefaultValue(column.getDefaultValue());
                                campoActual.setAllowNulls(column.isNullable());
                                campoActual.setSize(column.getSize());
                                campoActual.setComment(column.getRemarks());


                                // if there are remarks the finalname of the field
                                // its remarks, and also the finaltype....
                                if (!sf.cadena(campoActual.getComment()).equals("")) {
                                    String remarks = null;
                                    String comment = null;
                                    String targetType = null;

                                    remarks = sf.cadena(campoActual.getComment());
                                    // lets see the target type...
                                    if (remarks.contains("(")) {
                                        try {
                                            targetType = remarks.substring(remarks.indexOf("(") + 1, remarks.indexOf(")"));
                                            comment = remarks.substring(0, remarks.indexOf("("));

                                            campoActual.setComment(comment);

                                            if (targetType.toLowerCase().equals("image")) {
                                                campoActual.setTargetType(field.typeField._image);
                                            }
                                            if (targetType.toLowerCase().equals("audio")) {
                                                campoActual.setTargetType(field.typeField._audio);
                                            }
                                            if (targetType.toLowerCase().equals("document")) {
                                                campoActual.setTargetType(field.typeField._document);
                                            }
                                            if (targetType.toLowerCase().equals("ftb")) {
                                                campoActual.setTargetType(field.typeField._bigString);
                                            }
                                            campoActual.setTargetName(comment);

                                        } catch (Exception e) {
                                        }


                                    } else {
                                        campoActual.setTargetName(sf.cadena(campoActual.getComment()));
                                    }
                                } else {
                                    campoActual.setTargetName(column.getName());
                                }

                                camposTablaActual.add(campoActual);

                                ArrayList<relation> relaciones = new ArrayList<relation>();
                                // we get the relations...
                                if (column.isPartOfForeignKey()) {
                                    relation relacion = new relation();
                                    relacion = null;
                                    relacion = new relation();

                                    final Column primaryKeyColumn = column.getReferencedColumn();
                                    final NamedObject primaryKeyTable = primaryKeyColumn.getParent();

                                    relacion.setName(tablitaActual.getName() + "-" + primaryKeyTable.getName());
                                    info.append("\n Found relation : " + tablitaActual.getName() + "-" + primaryKeyTable.getName() + "\n");
                                    relacion.setParentKey(primaryKeyColumn.getName());
                                    relacion.setChildKey(column.getName());
                                    relacion.setChildTable(tablitaActual.getName());
                                    relacion.setParentTable(primaryKeyTable.getName());

                                    // we add extra description for the combos
                                    String comentarios = null;
                                    if (!column.getRemarks().equals("")) {
                                        comentarios = column.getRemarks();
                                    } else {
                                        comentarios = column.getName();
                                    }
                                    relacion.setDescriptionChild(comentarios);
                                    relacion.setDescriptionParent(comentarios);



                                    tablitaActual.addRelation(relacion);
                                    //relaciones.add(relacion);
                                    // relacion = null;


                                }
                            }

                            // actualizamos las tablas...
                            tablitaActual.setFields(camposTablaActual);


                            // make two arrays with fields key and not...
                            ArrayList<field> keyFields = new ArrayList<field>();
                            ArrayList<field> notKeyFields = new ArrayList<field>();
                            ArrayList<field> allFields = new ArrayList<field>();

                            ArrayList<String> parameters = new ArrayList<String>();
                            ArrayList<String> parametersForPhp = new ArrayList<String>();
                            ArrayList<String> parametersForCsharp = new ArrayList<String>();
                            ArrayList<String> parametersWithQuotes = new ArrayList<String>();

                            ArrayList<String> allFieldsWithQuotes = new ArrayList<String>();

                            String cadena;

                            // creamos unas cadenas-listas de utilidad para luego...
                            for (field campito : tablitaActual.getFields()) {
                                if (campito.getisKey()) {
                                    keyFields.add(campito);

                                    // para los parameters, utilizamos solo los campos clave ...
                                    switch (campito.getType()) {
                                        case _int: //int
                                            cadena = " int " + campito.getNombre();
                                            break;
                                        case _bigString:
                                            cadena = " String " + campito.getNombre();
                                            break;
                                        case _string: //string
                                            cadena = " String " + campito.getNombre();
                                            break;
                                        case _date: //date
                                            cadena = " Date " + campito.getNombre();
                                            break;
                                        case _boolean:  //boolean
                                            cadena = " boolean " + campito.getNombre();
                                            break;
                                        case _float:  //boolean
                                            cadena = " float " + campito.getNombre();
                                            break;
                                        default:
                                            cadena = " String " + campito.getNombre();
                                            break;
                                    }
                                    if (cadena != null) {
                                        parameters.add(cadena);
                                        // for php
                                        parametersForPhp.add("$" + campito.getNombre());
                                    }


                                } else {
                                    notKeyFields.add(campito);
                                    parametersWithQuotes.add("`" + campito.getNombre() + "`");
                                }

                                allFieldsWithQuotes.add("`" + campito.getNombre() + "`");
                                campito.setQuoted("`" + campito.getNombre() + "`");
                                allFields.add(campito);
                            }

                            // lets fill fields array...
                            tablitaActual.setFieldsKey(allFields);
                            tablitaActual.setFieldsWithoutKeys(notKeyFields);


                            // now we fill some variables...
                            tablitaActual.setlistaSoloCamposClave(util.join(keyFields, ","));
                            tablitaActual.setListWithAllTheFields(util.join(allFields, ","));
                            tablitaActual.setlistaTodosLosCamposSinCamposClave(util.join(notKeyFields, ","));
                            tablitaActual.setListParameters(util.join(parameters, ","));

                            tablitaActual.setListParametersForPhp(util.join(parametersForPhp, ","));

                            tablitaActual.setListFieldsWithQuotes(util.join(parametersWithQuotes, ","));
                            tablitaActual.setListAllFieldsWithQuotes(util.join(parametersWithQuotes, ","));


                            tablas.add(tablitaActual);


                        } else {
                        }


                    }



                    // code to found relations without relations defined
                    // some people asked it and some versions of mysql doesnt
                    // have relations so, lets go do it...
                    // if the field is key and it appears in another table
                    // there its a relation...
                    for (table tablita : tablas) {
                        for (field campito : tablita.getFields()) {
                            if (!campito.getisKey()) {
                                for (table tablitain : tablas) {
                                    for (field campito2 : tablitain.getFields()) {
                                        //if exists a table with that name...
                                        // skip if campito2 = idportal
                                        if (campito2.getisKey() && campito2.getNombre().toLowerCase().equals(campito.getNombre().toLowerCase()) && !campito2.getNombre().toLowerCase().equals("idportal")) {


                                            // we have to see if it exists...
                                            Boolean exists = false;
                                            for (relation rela : tablita.getRelations()) {
                                                String relas = "";
                                                relas = tablita + "-" + tablitain;
                                                if (rela.getName().toLowerCase().equals(relas.toLowerCase())) {
                                                    info.append("\n Found repeated relation : " + tablita + "-" + tablitain + "\n");
                                                    exists = true;

                                                } else {
                                                }
                                            }

                                            // theres no relation like this ...
                                            if (!exists) {
                                                campito.setisForeignKey((true));
                                                relation rel = new relation();
                                                rel.setName(tablita + "-" + tablitain);
                                                rel.setParentTable(tablitain.getName());
                                                rel.setParentKey(campito.getNombre());

                                                rel.setChildTable(tablita.getName());
                                                rel.setChildKey(campito.getNombre());

                                                // we add extra description for the combos
                                                rel.setDescriptionChild(tablitain.getFieldDescription());
                                                rel.setDescriptionParent(tablita.getFieldDescription());


                                                tablita.addRelation(rel);
                                                info.append("\n Found relation : " + rel.getName() + "\n");

                                            }




                                        }

                                    }
                                }
                            }

                        }
                    }
                    //end of code to found relations...
                }









            } catch (Exception ex) {
                info.append("Error : " + ex.getMessage() + "\n");
                info.append("Error : " + ex.toString() + "\n");
                info.append("Error class: " + ex.getStackTrace()[0].getClassName() + "\n");
                info.append("Error Metodo: " + ex.getStackTrace()[0].getMethodName() + "\n");
            }





            break;
        case 2: // postrgresql



            break;





        case 3: // sql server

            try {
//                // vamos a probar la conexion...
//                dbUtil db = new dbUtil();
//
//                final DataSource dataSource;
//                //dataSource = dbUtil.MakeDataSourceSqlServer(host.getText(), database.getText(), instance.getText(), user.getText(), password.getText(), port.getText());
//                dataSource = dbUtil.MakeDataSourceSqlServerJdts(host.getText(), instance.getText(), database.getText(), user.getText(), password.getText(), port.getText());
//
//                // Create the options
//                final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
//                options.setSchemaInfoLevel(SchemaInfoLevel.standard());
//                /*
//                options.setShowStoredProcedures(false);
//                options.setTableInclusionRule(new InclusionRule("C.*",   InclusionRule.EXCLUDE_NONE));
//                options.setColumnInclusionRule(new InclusionRule(InclusionRule.INCLUDE_ALL_PATTERN,
//                Pattern.compile(".*ID")));
//                options.setTableTypes("TABLE");
//                options.setAlphabeticalSortForTableColumns(true);
//                 */
//
//
//
//
//                final String excludesTablesPattern = "^(_|SYS|EX|PM|TMP|(CDI|MGMT|DBA|USER|CI|SDD|ALL|RM|TMP|TEST|DWH|SAV|SAVE)_).+$";


                // Get the schema definition
                // changed to maximum to get the relations between tables...
                //final Schema schema = SchemaCrawler.getSchema(dataSource, SchemaInfoLevel.maximum(), options);
                // final Database databasex = SchemaCrawlerUtility.getDatabase(dataSource.getConnection(), options);


                //   final Database databasex = dbUtil2.getDatabaseSqlServerJtds(host.getText(), instance.getText(), database.getText(), user.getText(), password.getText(), port.getText());
                final Database databasex = dbUtil2.getDatabaseSqlServer(host.getText(), instance.getText(), database.getText(), user.getText(), password.getText(), port.getText());


                //for (final Catalog catalog : databasex.getCatalogs()) {
                for (final Schema schema : databasex.getSchemas()) {
                    System.out.println(schema);
                    for (final Table table : schema.getTables()) {
                        System.out.print("o--> " + table);
                        if (table instanceof View) {
                            System.out.println(" (VIEW)");
                        } else {
                            System.out.println();
                        }

                        for (final Column column : table.getColumns()) {
                            System.out.println("     o--> " + column + " (" + column.getType() + ")");
                        }
                    }
                }
                // }

                //for (final Catalog catalog : databasex.getCatalogs()) {;
                //                    for (final Schema schema : catalog.getSchemas())
                //                    {
                //
                //                    }
                //
                //                }
                //                info.append("util.confDirectory : " + util.confDirectory + "\n");
                //                info.append("database bien : " + databasex.toString() + "\n");



                //final Catalog[] catalog = databasex..getCatalogs();
                final Schema[] catalog = databasex.getSchemas();


                // from all schemas we get dbo schema
                Schema schemaDbo = catalog[0];
                final Schema[] schemas = databasex.getSchemas();
                for (Schema schema : schemas) {
                    if (schema.toString().equals("dbo")) {
                        schemaDbo = schema;
                    }
                }

                final Schema schema = catalog[0];
                info.append("schema bien : " + schemaDbo.toString() + "\n");

                final Table[] tables = schemaDbo.getTables();

//                 for (int i = 0; i < tables.length; i++) {
//                   info.append("Tablas encontradas : " + tables[i].toString() + "\n");
//                }

                // final Table[] tables = schema.getTables();
                for (int i = 0; i < tables.length; i++) {
                    final Table table = tables[i];
                    info.append("Found table : " + table.getName() + "\n");
                    //System.out.print(table);


                    // le sacamos todos los datos...
                    // si no empieza por sys o por schema 
                    // (tablas del sistema sql server )
                    if (table.toString().indexOf("sys") == -1 && table.toString().indexOf("SCHEMA") == -1) {
                        tablitaActual = null;
                        tablitaActual = new table();

                        ArrayList<field> camposTablaActual = new ArrayList<field>();

                        tablitaActual.setName(table.getName());
                        tablitaActual.setTargetName(table.getName());



//                            if (table instanceof View) {
//                                System.out.println(" (view)");
//                            } else {
//                                System.out.println();
//                            }


                        final Column[] columns = table.getColumns();
                        for (int j = 0; j < columns.length; j++) {
                            final Column column = columns[j];
                            System.out.println("-- " + column);

                            campoActual = null;
                            campoActual = new field();
                            campoActual.setNombre(column.getName());
//                                if (column.isPartOfPrimaryKey())
//                                    campoActual.setIsKey();

                            int tipo = column.getType().getType();
                            campoActual.setTipo(tipo);
                            campoActual.setTargetType(tipo);


                            campoActual.setisKey(column.isPartOfPrimaryKey());
                            campoActual.setisForeignKey(column.isPartOfForeignKey());
                            campoActual.setDefaultValue(column.getDefaultValue());
                            campoActual.setAllowNulls(column.isNullable());
                            campoActual.setSize(column.getSize());
                            campoActual.setComment(column.getRemarks());

                            // if there are remarks the finalname of the field
                            // its remarks, and also the finaltype....
                            if (!sf.cadena(campoActual.getComment()).equals("")) {
                                String remarks = null;
                                String comment = null;
                                String targetType = null;

                                remarks = sf.cadena(campoActual.getComment());
                                // lets see the target type...
                                if (remarks.contains("(")) {
                                    try {
                                        targetType = remarks.substring(remarks.indexOf("(") + 1, remarks.indexOf(")"));
                                        comment = remarks.substring(0, remarks.indexOf("("));

                                        campoActual.setComment(comment);

                                        if (targetType.toLowerCase().equals("image")) {
                                            campoActual.setTargetType(field.typeField._image);
                                        }
                                        if (targetType.toLowerCase().equals("audio")) {
                                            campoActual.setTargetType(field.typeField._audio);
                                        }
                                        if (targetType.toLowerCase().equals("document")) {
                                            campoActual.setTargetType(field.typeField._document);
                                        }
                                        if (targetType.toLowerCase().equals("ftb")) {
                                            campoActual.setTargetType(field.typeField._bigString);
                                        }
                                        campoActual.setTargetName(comment);
                                    } catch (Exception e) {
                                    }


                                } else {
                                    campoActual.setTargetName(sf.cadena(campoActual.getComment()));
                                }
                            } else {
                                campoActual.setTargetName(column.getName());
                            }

//                            // if there are remarks the finalname of the field
//                            // its remarks ....
//                            if (!sf.cadena(campoActual.getComment()).equals("")) {
//                                campoActual.setTargetName(sf.cadena(campoActual.getComment()));
//                            } else {
//                                campoActual.setTargetName(column.getName());
//                            }

                            camposTablaActual.add(campoActual);

                            //ArrayList<relation> relaciones = new ArrayList<relation>();
                            // we get the relations...
                            if (column.isPartOfForeignKey()) {
                                relation relacion = new relation();
//                                relacion = null;
//                                relacion = new relation();

                                final Column primaryKeyColumn = column.getReferencedColumn();
                                final NamedObject primaryKeyTable = primaryKeyColumn.getParent();

                                relacion.setName(tablitaActual.getName() + "-" + primaryKeyTable.getName());
                                info.append("\n Found relation : " + tablitaActual.getName() + "-" + primaryKeyTable.getName() + "\n");
                                relacion.setParentKey(primaryKeyColumn.getName());
                                relacion.setChildKey(column.getName());
                                relacion.setChildTable(tablitaActual.getName());
                                relacion.setParentTable(primaryKeyTable.getName());

//                                // we add extra description for the combos
//                                String comentarios = null;
//                                if (!column.getRemarks().equals("")) {
//                                    comentarios = column.getRemarks();
//                                } else {
//                                    comentarios = column.getName();
//                                }
                                relacion.setDescriptionChild(tablitaActual.getName());
                                relacion.setDescriptionParent(primaryKeyTable.getName());

                                tablitaActual.addRelation(relacion);
                                //relaciones.add(relacion);
                                // relacion = null;
                            }
                            // tablitaActual.setrelations(relaciones);
                            //relaciones = null;


                        }

                        // actualizamos las tablas...
                        tablitaActual.setFields(camposTablaActual);


                        // make two arrays with fields key and not...
                        ArrayList<field> keyFields = new ArrayList<field>();
                        ArrayList<field> notKeyFields = new ArrayList<field>();
                        ArrayList<field> allFields = new ArrayList<field>();

                        ArrayList<String> parameters = new ArrayList<String>();
                        ArrayList<String> parametersForPhp = new ArrayList<String>();
                        ArrayList<String> parametersForCsharp = new ArrayList<String>();
                        ArrayList<String> parametersWithQuotes = new ArrayList<String>();

                        String cadena;

                        // creamos unas cadenas-listas de utilidad para luego...
                        for (field campito : tablitaActual.getFields()) {
                            if (campito.getisKey()) {
                                keyFields.add(campito);

                                // para los parameters, utilizamos solo los campos clave ...
                                switch (campito.getType()) {
                                    case _int: //int
                                        cadena = " int " + campito.getNombre();
                                        break;
                                    case _bigString:
                                        cadena = " String " + campito.getNombre();
                                        break;
                                    case _string: //string
                                        cadena = " String " + campito.getNombre();
                                        break;
                                    case _date: //date
                                        cadena = " Date " + campito.getNombre();
                                        break;
                                    case _boolean:  //boolean
                                        cadena = " boolean " + campito.getNombre();
                                        break;
                                    case _float:  //boolean
                                        cadena = " float " + campito.getNombre();
                                        break;
                                    default:
                                        cadena = " String " + campito.getNombre();
                                        break;
                                }
                                if (cadena != null) {
                                    parameters.add(cadena);
                                    // for php
                                    parametersForPhp.add("$" + campito.getNombre());

                                }


                            } else {
                                notKeyFields.add(campito);
                                parametersWithQuotes.add("`" + campito.getNombre() + "`");
                            }

                            allFields.add(campito);
                        }

                        // lets fill fields array...
                        tablitaActual.setFieldsKey(allFields);
                        tablitaActual.setFieldsWithoutKeys(notKeyFields);

                        // now we fill some variables...
                        tablitaActual.setlistaSoloCamposClave(util.join(keyFields, ","));
                        tablitaActual.setListWithAllTheFields(util.join(allFields, ","));
                        tablitaActual.setlistaTodosLosCamposSinCamposClave(util.join(notKeyFields, ","));
                        tablitaActual.setListParameters(util.join(parameters, ","));

                        tablitaActual.setListParametersForPhp(util.join(parametersForPhp, ","));

                        tablitaActual.setListFieldsWithQuotes(util.join(parametersWithQuotes, ","));

                        tablas.add(tablitaActual);


                    } else {
                    }

                }

                // code to found relations without relations defined
                // some people asked it
                // lets go do it...
                // if the field is key and it appears in another table
                // there its a relation...
                for (table tablita : tablas) {
                    for (field campito : tablita.getFields()) {
                        if (!campito.getisKey()) {
                            for (table tablitain : tablas) {
                                for (field campito2 : tablitain.getFields()) {
                                    //if exists a table with that name...
                                    if (campito2.getisKey() && campito2.getNombre().toLowerCase().equals(campito.getNombre().toLowerCase())) {


                                        // we have to see if it exists...
                                        Boolean exists = false;
                                        for (relation rela : tablita.getRelations()) {
                                            String relas = "";
                                            relas = tablita + "-" + tablitain;
                                            if (rela.getName().toLowerCase().equals(relas.toLowerCase()) || rela.getName().toLowerCase().equals("idportal")) {
                                                info.append("\n Found repeated relation : " + tablita + "-" + tablitain + "\n");
                                                exists = true;
                                            } else {
                                            }
                                        }

                                        if (!exists) {
                                            // theres no relation like this ...
                                            campito.setisForeignKey((true));
                                            relation rel = new relation();
                                            rel.setName(tablita + "-" + tablitain);
                                            rel.setParentTable(tablitain.getName());
                                            rel.setParentKey(campito.getNombre());

                                            rel.setChildTable(tablita.getName());
                                            rel.setChildKey(campito.getNombre());

                                            // we add extra description for the combos
                                            rel.setDescriptionChild(tablitain.getFieldDescription());
                                            rel.setDescriptionParent(tablita.getFieldDescription());


                                            tablita.addRelation(rel);
                                            info.append("\n Found relation : " + rel.getName() + "\n");

                                        }

                                    }

                                }
                            }
                        }

                    }
                }
                // end code of found relations...

            } catch (Exception ex) {
                info.append("Error : " + ex.getMessage() + "\n");
                info.append("Error : " + ex.toString() + "\n");
                info.append("Error class: " + ex.getStackTrace()[0].getClassName() + "\n");
                info.append("Error Metodo: " + ex.getStackTrace()[0].getMethodName() + "\n");
                info.append("Error Metodo: " + ex.getStackTrace().toString() + "\n");
            }
            break;



        case 4: // jdbc

            // schemacrawler doesnt work with jdbc so ....
            Connection con = null;
            PreparedStatement stmt = null;
            ResultSet rs = null;

            String sDriver = "sun.jdbc.odbc.JdbcOdbcDriver";
            String sURL = "jdbc:odbc:" + database.getText();

            try {
                Class.forName(sDriver).newInstance();
                con = DriverManager.getConnection(sURL, user.getText(), password.getText());
                DatabaseMetaData dbmd = con.getMetaData();

                ResultSet rsx = null;
//            if(showSystemTables) {
//                rs = dbmd.getTables(null, null, "%", null);
//            }
//            else {
//                rs = dbmd.getTables(null, null, "%", new String[] {"VIEW", "TABLE"});
//            }
                rsx = dbmd.getTables(null, null, "%", new String[]{"VIEW", "TABLE"});



                while (rsx.next()) {
//            TableInfo ti = new TableInfo();
                    String tableCat = rsx.getString("TABLE_CAT");
                    String tableSchema = rsx.getString(2);
                    String tableName = rsx.getString(3);
                    String tableType = rsx.getString(4);
                    String tableRemarks = rsx.getString(5);

                    // we got another table...
                    tablitaActual = null;
                    tablitaActual = new table();
                    tablitaActual.setName(tableName);
                    info.append("Found table : " + tableName + "\n");

                    ArrayList<field> camposTablaActual = new ArrayList<field>();

                    ResultSet rsColumns = dbmd.getColumns(null, null, tableName, "%");
                    while (rsColumns.next()) {
                        field campito = new field();


//                    el driver no permite esto...//
//                          campoActual.setisKey(column.isPartOfPrimaryKey());
//                            campoActual.setisForeignKey(column.isPartOfForeignKey());
//                            campoActual.setDefaultValue(column.getDefaultValue());
//                            campoActual.setAllowNulls(column.isNullable());
//                            campoActual.setSize(column.getSize());
//                            campoActual.setComment(column.getRemarks());


//            campito.setTableCatalog(rsColumns.getString(COLUMN.TABLE_CAT));
//            campito.setTableSchema(rsColumns.getString(COLUMN.TABLE_SCHEM));
//            campito.setTableName(rsColumns.getString(COLUMN.TABLE_NAME));
                        campito.setNombre(rsColumns.getString(COLUMN.COLUMN_NAME));
                        int tipito = rsColumns.getInt(COLUMN.DATA_TYPE);
                        campito.setTipo(tipito);
                        campito.setTargetType(tipito);

                        //campito.setTypeName(rsColumns.getString(COLUMN.TYPE_NAME));
                        campito.setSize(rsColumns.getInt(COLUMN.COLUMN_SIZE));
//            campito.set(rsColumns.getInt(COLUMN.DECIMAL_DIGITS));
//            campito.setRadix(rsColumns.getInt(COLUMN.NUM_PREC_RADIX));
                        campito.setAllowNulls(DatabaseMetaData.columnNoNulls != rsColumns.getInt(COLUMN.NULLABLE));
//            campito.setRemarks(rsColumns.getString(COLUMN.REMARKS));
                        campito.setDefaultValue(rsColumns.getString(COLUMN.COLUMN_DEF));
                        // campito.setOrdinal(rsColumns.getInt(COLUMN.ORDINAL_POSITION));


                        campito.setComment(rsColumns.getString(COLUMN.REMARKS));
                        // if there are remarks the finalname of the field
                        // its remarks ....



                        if (!sf.cadena(campito.getComment()).equals("")) {
                            campito.setTargetName(sf.cadena(campito.getComment()));
                        } else {
                            campito.setTargetName(campito.getNombre());
                        }
                        //campito.add(col);


                        camposTablaActual.add(campito);

                    }// actualizamos las tablas...

                    tablitaActual.setFields(camposTablaActual);


//// para sacar los campos clave
//                    ResultSet primaryKeys = dbmd.getPrimaryKeys(null, null, tablitaActual.getName());
//                    while (primaryKeys.next()) {
//                        String primaryKeyColumn = primaryKeys.getString("COLUMN_NAME");
//                        System.out.println("Primary Key Column: " + primaryKeyColumn);
//                        for (field campitox : tablitaActual.getFields()) {
//                            if (campitox.getNombre().equals(primaryKeyColumn))
//                            {
//                                campitox.setisKey(true);
//                            }
//                        }
//                    }




                    // now get the primarykeys...
                    // not for this jdbc
//                    ResultSet rsPks = dbmd.getPrimaryKeys(null, null, tableName);
//                   while (rsPks.next()) {
//                   }




                    // now the relations...
                    // with this jdbc its not possible...

//                    ArrayList<relation> relaciones = new ArrayList<relation>();
//                    ResultSet rsRelations = dbmd.getImportedKeys(null, null, tableName);
//                    while (rsRelations.next()) {
//
//                        relation rel = new relation();
//                        rel.setName(rsColumns.getString("PKTABLE_NAME") + "-" + rsColumns.getString("FKTABLE_NAME"));
//                        rel.setParentTable(rsColumns.getString("PKTABLE_NAME"));
//                        rel.setParentKey(rsColumns.getString("PKCOLUMN_NAME"));
//
//                        rel.setChildTable(rsColumns.getString("FKTABLE_NAME"));
//                        rel.setChildKey(rsColumns.getString("FKCOLUMN_NAME"));
//
//
//                        tablitaActual.addRelation(rel);
////                        PKTABLE_CAT String => primary key table catalog (may be null)
////PKTABLE_SCHEM String => primary key table schema (may be null)
////PKTABLE_NAME String => primary key table name
////PKCOLUMN_NAME String => primary key column name
////
////FKTABLE_CAT String => foreign key table catalog (may be null) being exported (may be null)
////FKTABLE_SCHEM String => foreign key table schema (may be null) being exported (may be null)
////FKTABLE_NAME String => foreign key table name being exported
////FKCOLUMN_NAME String => foreign key column name being exported
////
////KEY_SEQ short => sequence number within foreign key( a value of 1 represents the first column of the foreign key, a value of 2 would represent the second column within the foreign key).
////UPDATE_RULE short => What happens to foreign key when primary is updated:
//
//
//                    }



                    //how we cant identify relations neither primary keys
                    // lets use these two rules
                    // if the field starts with id and has the name of the table then its a key

                    for (field campito : tablitaActual.getFields()) {
                        campito.setisKey(campito.getNombre().startsWith("id") && campito.getNombre().toLowerCase().indexOf(tablitaActual.getName().toLowerCase()) != -1);
                    }


                    // make two arrays with fields key and not...
                    ArrayList<field> keyFields = new ArrayList<field>();
                    ArrayList<field> notKeyFields = new ArrayList<field>();
                    ArrayList<field> allFields = new ArrayList<field>();

                    ArrayList<String> parameters = new ArrayList<String>();
                    ArrayList<String> parametersForPhp = new ArrayList<String>();
                    ArrayList<String> parametersForCsharp = new ArrayList<String>();
                    ArrayList<String> parametersWithQuotes = new ArrayList<String>();

                    String cadena;

                    // creamos unas cadenas-listas de utilidad para luego...
                    for (field campito : tablitaActual.getFields()) {
                        if (campito.getisKey()) {
                            keyFields.add(campito);

                            // para los parameters, utilizamos solo los campos clave ...
                            switch (campito.getType()) {
                                case _int: //int
                                    cadena = " int " + campito.getNombre();
                                    break;
                                case _bigString:
                                case _string: //string
                                    cadena = " String " + campito.getNombre();
                                    break;
                                case _date: //date
                                    cadena = " Date " + campito.getNombre();
                                    break;
                                case _boolean:  //boolean
                                    cadena = " boolean " + campito.getNombre();
                                    break;
                                case _float:  //boolean
                                    cadena = " float " + campito.getNombre();
                                    break;
                                default:
                                    cadena = " String " + campito.getNombre();
                                    break;
                            }
                            if (cadena != null) {
                                parameters.add(cadena);
                                // for php
                                parametersForPhp.add("$" + campito.getNombre());
                            }


                        } else {
                            notKeyFields.add(campito);
                            parametersWithQuotes.add("`" + campito.getNombre() + "`");
                        }

                        allFields.add(campito);
                    }

                    // lets fill fields array...
                    tablitaActual.setFieldsKey(allFields);
                    tablitaActual.setFieldsWithoutKeys(notKeyFields);

                    // now we fill some variables...
                    tablitaActual.setlistaSoloCamposClave(util.join(keyFields, ","));
                    tablitaActual.setListWithAllTheFields(util.join(allFields, ","));
                    tablitaActual.setlistaTodosLosCamposSinCamposClave(util.join(notKeyFields, ","));
                    tablitaActual.setListParameters(util.join(parameters, ","));

                    tablitaActual.setListParametersForPhp(util.join(parametersForPhp, ","));

                    tablitaActual.setListFieldsWithQuotes(util.join(parametersWithQuotes, ","));

                    tablas.add(tablitaActual);
                }


                //how we cant identify relations neither primary keys
                // lets use these two rules
                // if the field starts with id then its a key
                // if exists a table with the name of the key there its
                // a relation

//                for (table tablita : tablas) {
//                    for (field campito : tablita.getFields()) {
//                        campito.setisKey(campito.getNombre().startsWith("id") && campito.getNombre().toLowerCase().indexOf(tablita.getNombre().toLowerCase()) != -1);
//                    }
//                }

                // code to found relations without relations defined
                // if the field is key and it appears in another table
                // there its a relation...
                for (table tablita : tablas) {
                    for (field campito : tablita.getFields()) {
                        if (campito.getNombre().startsWith("id") && !campito.getisKey()) {
                            String nombreTabla = campito.getNombre().substring(2);
                            for (table tablitain : tablas) {
                                //if exists a table with that name...
                                if (tablitain.getName().toLowerCase().equals(nombreTabla.toLowerCase())) {
                                    campito.setisForeignKey((true));
                                    relation rel = new relation();
                                    rel.setName(tablita + "-" + tablitain);
                                    rel.setParentTable(tablitain.getName());
                                    rel.setParentKey(campito.getNombre());

                                    rel.setChildTable(tablita.getName());
                                    rel.setChildKey(campito.getNombre());
                                    tablita.addRelation(rel);
                                    info.append("\n Found relation : " + rel.getName() + "\n");

                                }
                            }
                        }

                    }
                }
                // end code of found relations...




            } catch (SQLException sqle) {

                info.append("\n" + "Error : " + sqle.getMessage() + "\n");
                sqle.printStackTrace();
            } catch (Exception e) {
                info.append("\n" + "Error : " + e.getMessage() + "\n");
                e.printStackTrace();
            } finally {
                if (con != null) {
                    try {
                        rs.close();
                        stmt.close();
                        con.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }




            break;



        case 5: // sqlExpress


            try {
                // vamos a probar la conexion...
                dbUtil db = new dbUtil();

                final DataSource dataSource;

                dataSource = dbUtil.MakeDataSourceSqlExpress(host.getText(), database.getText(), user.getText(), password.getText(), port.getText());

                // Create the options
                final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
                /*
                options.setShowStoredProcedures(false);
                options
                .setTableInclusionRule(new InclusionRule("C.*",
                InclusionRule.EXCLUDE_NONE));
                options
                .setColumnInclusionRule(new InclusionRule(InclusionRule.INCLUDE_ALL_PATTERN,
                Pattern.compile(".*ID")));
                options.setTableTypes("TABLE");
                options.setAlphabeticalSortForTableColumns(true);
                 */




                final String excludesTablesPattern = "^(_|SYS|EX|PM|TMP|(CDI|MGMT|DBA|USER|CI|SDD|ALL|RM|TMP|TEST|DWH|SAV|SAVE)_).+$";


                // Get the schema definition
                // changed to maximum to get the relations between tables...
                //final Schema schema = SchemaCrawler.getSchema(dataSource, SchemaInfoLevel.maximum(), options);

                final Database database = SchemaCrawlerUtility.getDatabase(dataSource.getConnection(), options);
                final Schema[] catalog = database.getSchemas();
                final Schema schema = catalog[0];

                final Table[] tables = schema.getTables();
                for (int i = 0; i < tables.length; i++) {
                    final Table table = tables[i];
                    System.out.print(table);


                    // le sacamos todos los datos...
                    // si no empieza por sys o por schema 
                    // (tablas del sistema sql server )
                    if (table.toString().indexOf("sys") == -1 && table.toString().indexOf("SCHEMA") == -1) {
                        tablitaActual = null;
                        tablitaActual = new table();

                        ArrayList<field> camposTablaActual = new ArrayList<field>();

                        tablitaActual.setName(table.getName());
                        tablitaActual.setTargetName(table.getName());

                        info.append("Found table : " + table.getName() + "\n");


                        final Column[] columns = table.getColumns();
                        for (int j = 0; j < columns.length; j++) {
                            final Column column = columns[j];
                            System.out.println("-- " + column);

                            campoActual = null;
                            campoActual = new field();
                            campoActual.setNombre(column.getName());
//                                if (column.isPartOfPrimaryKey())
//                                    campoActual.setIsKey();

                            int tipo = column.getType().getType();
                            campoActual.setTipo(tipo);
                            campoActual.setTargetType(tipo);

                            campoActual.setisKey(column.isPartOfPrimaryKey());
                            campoActual.setisForeignKey(column.isPartOfForeignKey());
                            campoActual.setDefaultValue(column.getDefaultValue());
                            campoActual.setAllowNulls(column.isNullable());
                            campoActual.setSize(column.getSize());
                            campoActual.setComment(column.getRemarks());

                            // if there are remarks the finalname of the field
                            // its remarks ....
                            if (!column.getRemarks().equals("")) {
                                campoActual.setTargetName(column.getRemarks());
                            } else {
                                campoActual.setTargetName(column.getName());
                            }


                            camposTablaActual.add(campoActual);

                            //ArrayList<relation> relaciones = new ArrayList<relation>();
                            // we get the relations...
                            if (column.isPartOfForeignKey()) {
                                relation relacion = new relation();
//                                relacion = null;
//                                relacion = new relation();

                                final Column primaryKeyColumn = column.getReferencedColumn();
                                final NamedObject primaryKeyTable = primaryKeyColumn.getParent();

                                relacion.setName(tablitaActual.getName() + "-" + primaryKeyTable.getName());
                                info.append("\n Found relation : " + tablitaActual.getName() + "-" + primaryKeyTable.getName() + "\n");
                                relacion.setParentKey(primaryKeyColumn.getName());
                                relacion.setChildKey(column.getName());
                                relacion.setChildTable(tablitaActual.getName());
                                relacion.setParentTable(primaryKeyTable.getName());

                                tablitaActual.addRelation(relacion);
                                //relaciones.add(relacion);
                                // relacion = null;
                            }
                            // tablitaActual.setrelations(relaciones);
                            //relaciones = null;




                        }

                        // actualizamos las tablas...
                        tablitaActual.setFields(camposTablaActual);


                        // make two arrays with fields key and not...
                        ArrayList<field> keyFields = new ArrayList<field>();
                        ArrayList<field> notKeyFields = new ArrayList<field>();
                        ArrayList<field> allFields = new ArrayList<field>();

                        ArrayList<String> parameters = new ArrayList<String>();
                        ArrayList<String> parametersForPhp = new ArrayList<String>();
                        ArrayList<String> parametersForCsharp = new ArrayList<String>();
                        ArrayList<String> parametersWithQuotes = new ArrayList<String>();

                        String cadena;

                        // creamos unas cadenas-listas de utilidad para luego...
                        for (field campito : tablitaActual.getFields()) {
                            if (campito.getisKey()) {
                                keyFields.add(campito);

                                // para los parameters, utilizamos solo los campos clave ...
                                switch (campito.getType()) {
                                    case _int: //int
                                        cadena = " int " + campito.getNombre();
                                        break;
                                    case _bigString:
                                    case _string: //string
                                        cadena = " String " + campito.getNombre();
                                        break;
                                    case _date: //date
                                        cadena = " Date " + campito.getNombre();
                                        break;
                                    case _boolean:  //boolean
                                        cadena = " boolean " + campito.getNombre();
                                        break;
                                    case _float:  //boolean
                                        cadena = " float " + campito.getNombre();
                                        break;
                                    default:
                                        cadena = " String " + campito.getNombre();
                                        break;
                                }
                                if (cadena != null) {
                                    parameters.add(cadena);
                                    // for php
                                    parametersForPhp.add("$" + campito.getNombre());

                                }


                            } else {
                                notKeyFields.add(campito);
                                parametersWithQuotes.add("`" + campito.getNombre() + "`");



                            }

                            allFields.add(campito);
                        }

                        // lets fill fields array...
                        tablitaActual.setFieldsKey(allFields);
                        tablitaActual.setFieldsWithoutKeys(notKeyFields);

                        // now we fill some variables...
                        tablitaActual.setlistaSoloCamposClave(util.join(keyFields, ","));
                        tablitaActual.setListWithAllTheFields(util.join(allFields, ","));
                        tablitaActual.setlistaTodosLosCamposSinCamposClave(util.join(notKeyFields, ","));
                        tablitaActual.setListParameters(util.join(parameters, ","));

                        tablitaActual.setListParametersForPhp(util.join(parametersForPhp, ","));

                        tablitaActual.setListFieldsWithQuotes(util.join(parametersWithQuotes, ","));

                        tablas.add(tablitaActual);


                    } else {
                    }


                }
            } catch (Exception ex) {
                info.append("Error : " + ex.getMessage() + "\n");
                info.append("Error : " + ex.toString() + "\n");
                info.append("Error class: " + ex.getStackTrace()[0].getClassName() + "\n");
                info.append("Error Metodo: " + ex.getStackTrace()[0].getMethodName() + "\n");
            }
            break;
    }


    proyectoActual.setNombre(nombre.getText());
    proyectoActual.setHost(host.getText());
    proyectoActual.setInstance(instance.getText());
    proyectoActual.setuser(user.getText());
    proyectoActual.setpassword(password.getText());
    proyectoActual.setPort(port.getText());
    proyectoActual.setDescription(description.getText());


    String ap = applicationDirectory.getText();
    if (!ap.endsWith("\\")) {
        ap = ap + "\\";
    }
    proyectoActual.setApplicationDirectory(ap);
    proyectoActual.setProjectTemplatesDirectory(projectTemplatesDirectory.getText());
    int seleccionado2 = jComboBox1.getSelectedIndex();

    switch (seleccionado2) {
        case 1: // mysql

            proyectoActual.setTypeOfDataBase(dbDataType.MySql);
            break;

        case 2: // postrgresql
            proyectoActual.setTypeOfDataBase(dbDataType.PostgreSql);
            break;

        case 3: // sql server
            proyectoActual.setTypeOfDataBase(dbDataType.SqlServer);
            break;

        case 4: // jdbc
            proyectoActual.setTypeOfDataBase(dbDataType.Jdbc);
            break;
        case 5: // sqlExpress
            proyectoActual.setTypeOfDataBase(dbDataType.SqlExpress);
            break;

    }




    proyectoActual.setdatabase(database.getText());
//            proyectoActual.setDescrpcion(port.getText()); 
//            proyectoActual.setPort(port.getText()); 



    proyectoActual.setTablas(tablas);
    try {
        if (!nombre.getText().equals("")) {
            proyectoActual.saveProject(proyectoActual);
            info.append(" \n Project saved : " + nombre.getText() + ".ule \n");

            // Delay to wait
            //  Thread.sleep(4000);
            //   this.setVisible(false);
        }

    } catch (Exception ex) {
        info.append("Error : " + ex.getMessage() + "\n");
    }

    this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    NProject = proyectoActual;
    panelDatos.setVisible(true);

}//GEN-LAST:event_butSaveConnectionMouseClicked

private void butSaveConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSaveConnectionActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_butSaveConnectionActionPerformed

private void jComboBox1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jComboBox1MouseClicked
// TODO add your handling code here:
}//GEN-LAST:event_jComboBox1MouseClicked

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
// TODO add your handling code here:
    int seleccionado = jComboBox1.getSelectedIndex();

    // to set line wrap in the help window...
    jtHelp.setLineWrap(true);
    switch (seleccionado) {
        case 1: // mysql
            String message0 = "To connect to MySql ...";
            message0 = message0.concat("\n For example to connect to a database called datab1 in an instance of mySql in the ip 192.168.0.135 with user root and password saxxx, you must provide the next data:");
            message0 = message0.concat("\n server: 192.168.0.135");
            message0 = message0.concat("\n user: root");
            message0 = message0.concat("\n password: saxx");
            message0 = message0.concat("\n ");
            jtHelp.setText(message0);
            port.setText("3306");
            break;

        case 2: // postrgresql

            port.setText("1400");

            String message2 = "PostgreSql not implemented still ...";
            //message2 = message2.concat("\n For example to connect to a database called datab1 in an instance of mySql in the ip 192.168.0.135 with user root and password saxxx, you must provide the next data:");

            jtHelp.setText(message2);
            break;

        case 3: // sql server
            String message3 = "To connect to Sql Server ... \n Remember if youre using an instance to put the name of the instance in the host name...";
            message3 = message3.concat("\n For example to connect to a database called datab1 in an instance of sql server 2005 in the ip 192.168.0.135 with user sa and password saxxx, you must provide the next data:");
            message3 = message3.concat("\n server: 192.168.0.135\\SQL2005");
            message3 = message3.concat("\n user: sa");
            message3 = message3.concat("\n password: saxx");
            message3 = message3.concat("\n database: datab1");
            message3 = message3.concat("\n ");
            message3 = message3.concat("\n We dont use the port cause from 2005 the ports are dynamics...");

            jtHelp.setText(message3);

            port.setText("");
            break;

        case 4: // jdbc
            String message4 = "To connect to jdbc you will only need set the database field with the name of the dsn. \n \n Note: the jdbc driver doesnt work properly, so the relations and keyfiels...";
            jtHelp.setText(message4);

            port.setText("");
            break;

        case 5: // sqlExpress
            String message5 = "· You need to enable mixed mode security when you install the server so that you can connect using user name and password.";
            message5 += "· Make sure that the sqlbrowser is enabled.  Sql Server configuration Manager ->SQL Server 2005 Services ->SQL Server Browser ->Start";
            message5 += "· The JDBC provider only works with the TCP/IP protocol which is disabled by default on Sql Express. You need to enable the TCP/IP Protocol from the SQL Server Configuration Manager that ships with SqlExpress and re-start the server. Look under SQL Server 2005 Network Configuration -> Protocols for SQLEXPRESS-> TCP/IP->Enable.";

            jtHelp.setText(message5);

            host.setText(".\\sqlexpress");
            port.setText("");
            break;

    }

}//GEN-LAST:event_jComboBox1ActionPerformed

private void butWorkingDirectory1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butWorkingDirectory1MouseClicked
    JFileChooser directoryChooser;
    directoryChooser = new JFileChooser();
    directoryChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    directoryChooser.setCurrentDirectory(new File(util.templateProjectsDirectory));
//    directoryChooser.setFileFilter(new jule.uleFilterFiles());
    directoryChooser.setDialogTitle("Choose directory where the Project template its...");
    directoryChooser.setApproveButtonText("Choose directory");
    //directoryChooser.showOpenDialog(null);

    if (directoryChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        File file = directoryChooser.getSelectedFile();
        if (file != null) {
            projectTemplatesDirectory.setText(file.getPath());
        }
    }
}//GEN-LAST:event_butWorkingDirectory1MouseClicked

private void butWorkingDirectoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butWorkingDirectoryActionPerformed

    // we need the name of the directory to work in all systems...
    File initialDirectory = null;
    File canonicalDirectory = null;
    try {
        initialDirectory = new File(util.userHome);//new File(txtDirectory.getText());
        if (initialDirectory != null) {
            canonicalDirectory = new File(initialDirectory.getCanonicalPath());
        }



    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
    }

    try {
        if (canonicalDirectory != null) {
            JFileChooser directoryChooser2;
            directoryChooser2 = new JFileChooser();
            directoryChooser2.setDialogTitle("Choose directory where the generated code goes...");
            directoryChooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            directoryChooser2.setCurrentDirectory(new File("."));
            directoryChooser2.setApproveButtonText("Choose directory");
            // directoryChooser2.showOpenDialog(null);

            if (directoryChooser2.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                File file = directoryChooser2.getSelectedFile();
                if (file != null) {
                    applicationDirectory.setText(file.getPath());
                }
            }



        }
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
    }


}//GEN-LAST:event_butWorkingDirectoryActionPerformed

private void butSaveConnectionOnlyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_butSaveConnectionOnlyMouseClicked
    // TODO add your handling code here:
}//GEN-LAST:event_butSaveConnectionOnlyMouseClicked

private void butSaveConnectionOnlyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_butSaveConnectionOnlyActionPerformed
    // TODO add your handling code here:

    // saves only the data of the main panel, not refresh metadata..
    int seleccionado = jComboBox1.getSelectedIndex();
    boolean seguir = false;


    // declaraciones para crear el proyecto...
    project proyectoActual = new project();
    if (this.NProject == null) {
    } else {
        proyectoActual = this.NProject;
    }

    proyectoActual.setNombre(nombre.getText());
    proyectoActual.setHost(host.getText());
    proyectoActual.setInstance(instance.getText());
    proyectoActual.setuser(user.getText());
    proyectoActual.setpassword(password.getText());
    proyectoActual.setPort(port.getText());
    proyectoActual.setDescription(description.getText());


    String ap = applicationDirectory.getText();
    if (!ap.endsWith("\\")) {
        ap = ap + "\\";
    }
    proyectoActual.setApplicationDirectory(ap);
    proyectoActual.setProjectTemplatesDirectory(projectTemplatesDirectory.getText());
    int seleccionado2 = jComboBox1.getSelectedIndex();

    switch (seleccionado2) {
        case 1: // mysql

            proyectoActual.setTypeOfDataBase(dbDataType.MySql);
            break;

        case 2: // postrgresql
            proyectoActual.setTypeOfDataBase(dbDataType.PostgreSql);
            break;

        case 3: // sql server
            proyectoActual.setTypeOfDataBase(dbDataType.SqlServer);
            break;

        case 4: // jdbc
            proyectoActual.setTypeOfDataBase(dbDataType.Jdbc);
            break;
        case 5: // sqlExpress
            proyectoActual.setTypeOfDataBase(dbDataType.SqlExpress);
            break;

    }


    proyectoActual.setdatabase(database.getText());
//            proyectoActual.setDescrpcion(port.getText());
//            proyectoActual.setPort(port.getText());



    try {
        if (!nombre.getText().equals("")) {
            proyectoActual.saveProject(proyectoActual);
            info.append(" \n Project saved : " + nombre.getText() + ".ule \n");

            // Delay to wait
            //  Thread.sleep(4000);
            //   this.setVisible(false);
        }

    } catch (Exception ex) {
        info.append("Error : " + ex.getMessage() + "\n");
    }

    NProject = proyectoActual;
    panelDatos.setVisible(true);

}//GEN-LAST:event_butSaveConnectionOnlyActionPerformed

private void hostPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_hostPropertyChange
    // TODO add your handling code here:
}//GEN-LAST:event_hostPropertyChange

private void hostFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_hostFocusLost
    if (host.getText().contains("\\")) {
        String string1 = "";
        String string2 = "";
        int position = 0;
        position = host.getText().indexOf("\\");
        string1 = host.getText().substring(0, position);
        string2 = host.getText().substring(position + 1, host.getText().length());

        host.setText(string1);
        instance.setText(string2);

    }
}//GEN-LAST:event_hostFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                editProject dialog = new editProject(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }//    protected void assignForeignKeys(final Schema schema, table tablita) {
//        for (final Table table : schema.getTables()) {
//            for (final Column column : table.getColumns()) {
//                if (column.isPartOfForeignKey()) {
//                    
//                    // we got another relation...
//                    
//                    final Column primaryKeyColumn = column.getReferencedColumn();
//                    final NamedObject primaryKeyTable = primaryKeyColumn.getParent();
//                    final TableMetaData primaryKeyTableMetaData = schemaMetaData.getTable(primaryKeyTable.getName());
//                    final TableMetaDataColumn primaryKeyColumnMetaData = primaryKeyTableMetaData.getColumn(primaryKeyColumn.getName());
//                    final TableMetaData foreignKeyTableMetaData = schemaMetaData.getTable(table.getName());
//                    final TableMetaDataColumn foreignKeyColumnMetaData = foreignKeyTableMetaData.getColumn(column.getName());
//                    foreignKeyColumnMetaData.setReferencedColumn(primaryKeyColumnMetaData);
//                    primaryKeyTableMetaData.addReference(foreignKeyColumnMetaData);
//                }
//            }
//        }
//    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField applicationDirectory;
    private javax.swing.JButton butProbarConexion;
    private javax.swing.JButton butSaveConnection;
    private javax.swing.JButton butSaveConnectionOnly;
    private javax.swing.JButton butWorkingDirectory;
    private javax.swing.JButton butWorkingDirectory1;
    private javax.swing.JTextField database;
    private javax.swing.JTextField description;
    private javax.swing.JTextField host;
    private javax.swing.JTextArea info;
    private javax.swing.JTextField instance;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea jtHelp;
    private javax.swing.JTextField nombre;
    private javax.swing.JPanel panelDatos;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField port;
    private javax.swing.JTextField projectTemplatesDirectory;
    private javax.swing.JTextField user;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
